import axios from 'axios';
import { ARTICLE_API } from './apiUrl';
import type { 
  ArticleSearchParams, 
  ArticleListResponse,
  ArticleItem,
  ApiResponse
} from './types';

// 查询文章列表
export const searchArticles = async (params: ArticleSearchParams): Promise<ArticleListResponse> => {
  try {
    const response = await axios.get<ArticleListResponse>(ARTICLE_API.SEARCH, { params });
    return response.data;
  } catch (error) {
    console.error('查询文章列表失败:', error);
    throw error;
  }
};

// 获取文章详情
export const getArticleDetail = async (id: number, tableName?: string): Promise<ApiResponse<ArticleItem>> => {
  try {
    const params = tableName ? { tableName } : undefined;
    const response = await axios.get(`${ARTICLE_API.DETAIL}/${id}`, { params });
    return response.data;
  } catch (error) {
    console.error('获取文章详情失败:', error);
    throw error;
  }
};

// 添加文章
export const addArticle = async (article: Omit<ArticleItem, 'id'>): Promise<ApiResponse> => {
  try {
    const response = await axios.post(ARTICLE_API.ADD, article);
    return response.data;
  } catch (error) {
    console.error('添加文章失败:', error);
    throw error;
  }
};

// 更新文章
export const updateArticle = async (article: ArticleItem, tableName?: string): Promise<ApiResponse> => {
  try {
    const params = tableName ? { tableName } : undefined;
    const response = await axios.put(`${ARTICLE_API.UPDATE}/${article.id}`, article, { params });
    return response.data;
  } catch (error) {
    console.error('更新文章失败:', error);
    throw error;
  }
};

// 删除文章
export const deleteArticle = async (id: number, tableName?: string): Promise<ApiResponse> => {
  try {
    const params = tableName ? { tableName } : undefined;
    const response = await axios.post(`${ARTICLE_API.DELETE}/${id}`, null, { params });
    return response.data;
  } catch (error) {
    console.error('删除文章失败:', error);
    throw error;
  }
};

// 更新文章状态（推荐状态或有效状态）
export const updateArticleStatus = async (
  id: number, 
  field: 'recommend' | 'active', 
  value: number,
  tableName?: string
): Promise<ApiResponse> => {
  try {
    const data = { id, field, value };
    const params = tableName ? { tableName } : undefined;
    const response = await axios.patch(ARTICLE_API.UPDATE_STATUS, data, { params });
    return response.data;
  } catch (error) {
    console.error('更新文章状态失败:', error);
    throw error;
  }
};

// 批量导入文章
export const importArticles = async (
  file: File,
  params: {
    catename?: string;
    tableName?: string;
  }
): Promise<ApiResponse<{
  total: number;
  success: number;
  fail: number;
  errors: Array<{
    title: string;
    error: string;
  }>;
}>> => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await axios.post(ARTICLE_API.IMPORT, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      params // 将参数添加到URL query中
    });
    
    return response.data;
  } catch (error) {
    console.error('批量导入文章失败:', error);
    throw error;
  }
};

// 文章生效控制
export const toggleArticleActive = async (
  id: number, 
  active?: number, 
  tableName?: string
): Promise<ApiResponse<{id: number, active: number}>> => {
  try {
    const url = `${ARTICLE_API.TOGGLE_ACTIVE}/${id}`;
    const params = tableName ? { tableName } : undefined;
    const data = active !== undefined ? { active } : {};
    
    const response = await axios.post(url, data, { params });
    return response.data;
  } catch (error) {
    console.error('更新文章生效状态失败:', error);
    throw error;
  }
};

// 文章推荐控制
export const toggleArticleRecommend = async (
  id: number, 
  recommend?: number, 
  tableName?: string
): Promise<ApiResponse<{id: number, recommend: number}>> => {
  try {
    const url = `${ARTICLE_API.TOGGLE_RECOMMEND}/${id}`;
    const params = tableName ? { tableName } : undefined;
    const data = recommend !== undefined ? { recommend } : {};
    
    const response = await axios.post(url, data, { params });
    return response.data;
  } catch (error) {
    console.error('更新文章推荐状态失败:', error);
    throw error;
  }
}; 